package com.xm.common.mapper;

import com.xm.common.entity.dto.HistoryData;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;

@Mapper
public interface HistoryMapper {
    @SelectProvider(type = HistoryDataSqlProvider.class, method = "buildDynamicQuery")
    @Results(id = "dynamicResultMap", value = {
            @Result(property = "timestamp", column = "timestamp"),
            @Result(property = "clientId", column = "clientId"),
            @Result(property = "cpuUsage", column = "cpuUsage"),
            @Result(property = "memoryUsage", column = "memoryUsage"),
            @Result(property = "diskUsage", column = "diskUsage"),
            @Result(property = "diskRead", column = "diskRead"),
            @Result(property = "diskWrite", column = "diskWrite"),
            @Result(property = "networkUpload", column = "networkUpload"),
            @Result(property = "networkDownload", column = "networkDownload")
    })
    List<HistoryData> selectDynamicData(
            @Param("tableName") String tableName,
            @Param("clientId") Integer clientId,
            @Param("start") Long start,
            @Param("end") Long end,
            @Param("metricType") String metricType
    );

    class HistoryDataSqlProvider {
        public String buildDynamicQuery(
                @Param("tableName") String tableName,
                @Param("clientId") Integer clientId,
                @Param("start") Long start,
                @Param("end") Long end,
                @Param("metricType") String metricType
        ) {
            return new SQL() {{
                SELECT(resolveColumns(metricType));
                FROM(tableName);
                WHERE("client_id = #{clientId}");
                WHERE("timestamp BETWEEN #{start} AND #{end}");
                ORDER_BY("timestamp");
            }}.toString();
        }

        private String resolveColumns(String metricType) {
            return switch (metricType) {
                case "CPU" -> "timestamp, client_id AS clientId, cpu_usage AS cpuUsage";
                case "MEMORY" -> "timestamp, client_id AS clientId, memory_usage AS memoryUsage";
                case "DISK" -> "timestamp, client_id AS clientId, disk_usage AS diskUsage";
                case "DISK-IO" -> "timestamp, client_id AS clientId, disk_read AS diskRead, disk_write AS diskWrite";
                case "NETWORK" -> "timestamp, client_id AS clientId, network_upload AS networkUpload, network_download AS networkDownload";
                default -> throw new IllegalArgumentException("无效的指标类型");
            };
        }
    }
}
